package com.njtoyo.taxi.admin.service.local_service.merchant.impl;

import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.njtoyo.taxi.admin.cache.PrimaryCachePutter;
import com.njtoyo.taxi.admin.library.common.OperationRecordHelper;
import com.njtoyo.taxi.admin.mapper.master.entity.local_service.*;
import com.njtoyo.taxi.admin.mapper.master.mapper.local_service.*;
import com.njtoyo.taxi.admin.rest.presenter.local_service.merchant.LifeMerchantAccountPresenter;
import com.njtoyo.taxi.admin.rest.wrapper.local_service.merchant.LifeMerchantAccountAddWrapper;
import com.njtoyo.taxi.admin.rest.wrapper.local_service.merchant.LifeMerchantAccountUpdateWrapper;
import com.njtoyo.taxi.admin.rest.wrapper.local_service.merchant.LifeMerchantAccountWrapper;
import com.njtoyo.taxi.admin.service.local_service.merchant.MerchantAccountService;
import com.njtoyo.taxi.entity.backend.AdminUser;
import com.taxi.entity.common.RestResult;
import com.taxi.entity.common.ResultEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static cn.hutool.core.bean.BeanUtil.copyProperties;
import static cn.hutool.core.util.ObjectUtil.isEmpty;
import static cn.hutool.core.util.ObjectUtil.isNotEmpty;
import static java.util.stream.Collectors.toList;

@Slf4j
@Service
public class MerchantAccountServiceImpl implements MerchantAccountService {

    @Autowired
    private OperationRecordHelper operationRecordHelper;

    @Autowired
    private LifeMerchantMapper lifeMerchantMapper;

    @Autowired
    private LifeMerchantAccountMapper lifeMerchantAccountMapper;

    @Autowired
    private LifeMerchantAccountAddressMappingMapper lifeMerchantAccountAddressMappingMapper;

    @Autowired
    private LifeMerchantAddressMappingMapper lifeMerchantAddressMappingMapper;

    @Autowired
    private LifeAddressMapper lifeAddressMapper;

    @Autowired
    private PrimaryCachePutter primaryCachePutter;

    /**
     * 商户账号列表
     *
     * @param adminUser
     * @param wrapper
     * @return
     */
    @Override
    public RestResult<Page<LifeMerchantAccountPresenter>> getPage(AdminUser adminUser, LifeMerchantAccountWrapper wrapper) {
        switch (adminUser.getAccountType()) {
            case platform:
                break;
            default:
                return RestResult.failed("账号权限不够");
        }
        Page<LifeMerchantAccountPresenter> page = lifeMerchantAccountMapper.getPage(wrapper);
        List<LifeMerchantAccountPresenter> list = page.getRecords();
        if (isNotEmpty(list)) {
            List<Long> adressIds = list.stream()
                    .map(LifeMerchantAccountPresenter::getAddressId).collect(toList());
            List<Long> merchantIds = list.stream()
                    .map(LifeMerchantAccountPresenter::getMerchantId).collect(toList());

            //商户账号表关联的地址ID
            QueryWrapper<LifeAddress> addressWrapper = new QueryWrapper<>();
            addressWrapper.in("id", adressIds);
            List<LifeAddress> addressList = lifeAddressMapper.selectList(addressWrapper);

            //商户名称
            QueryWrapper<LifeMerchant> merchantQueryWrapper = new QueryWrapper<>();
            merchantQueryWrapper.select("id", "name");
            merchantQueryWrapper.in("id", merchantIds);
            List<Map<String, Object>> maps = lifeMerchantMapper.selectMaps(merchantQueryWrapper);
            Map<Long, String> map = maps.stream().collect(Collectors.toMap(i -> Long.valueOf(i.get("id").toString()), i -> i.get("name").toString()));

            list.forEach(LifeMerchantAccountPresenter -> {
                LifeMerchantAccountPresenter.setMerchantName(map.getOrDefault(LifeMerchantAccountPresenter.getMerchantId(), null));

                Long addressId = LifeMerchantAccountPresenter.getAddressId();
                addressList.forEach(lifeAddress -> {
                    Long lifeAddressId = lifeAddress.getId();
                    if (isNotEmpty(addressId)) {
                        if (addressId.equals(lifeAddressId)) {
                            LifeMerchantAccountPresenter.setAddress(lifeAddress.getAddress());
                            LifeMerchantAccountPresenter.setCategory(lifeAddress.getCategory());
                            LifeMerchantAccountPresenter.setAddressName(lifeAddress.getName());
                        }
                    }
                });

            });
        }
        return RestResult.success(page);
    }

    /**
     * 商户账号添加
     *
     * @param wrapper
     * @return
     */
    @Override
    @DSTransactional
    public RestResult add(LifeMerchantAccountAddWrapper wrapper) {
        Long merchantId = wrapper.getMerchantId();
        LifeMerchant lifeMerchant = lifeMerchantMapper.selectById(merchantId);
        if (isEmpty(lifeMerchant)) {
            return RestResult.build(ResultEnum.NOT_FOUND);
        }
        LifeMerchantAccount lifeMerchantAccount = copyProperties(wrapper, LifeMerchantAccount.class);

        //检验手机号不能重复
        String mobileNumber = lifeMerchantAccount.getMobileNumber();
        QueryWrapper<LifeMerchantAccount> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile_number", mobileNumber);
        Integer count = lifeMerchantAccountMapper.selectCount(queryWrapper);
        if (count > 0) {
            return RestResult.failed("手机号已被使用");
        }

        //生成密码
        String password = lifeMerchantAccount.getPassword();
        String md5 = DigestUtils.md5Hex(password);
        lifeMerchantAccount.setPassword(md5);
        lifeMerchantAccountMapper.insert(lifeMerchantAccount);
        Long id = lifeMerchantAccount.getId();

        //获取商户的地址关联
        Long addressId = wrapper.getAddressId();
        Long landId = null;
        if (isEmpty(addressId)) {
            LifeMerchantAddressMapping lifeAddressId = lifeMerchantAddressMappingMapper.getAddressId(merchantId);
            landId = lifeAddressId.getAddressId();
        }

        //地址绑定
        LifeMerchantAccountAddressMapping lifeMerchantAccountAddressMapping = new LifeMerchantAccountAddressMapping();
        lifeMerchantAccountAddressMapping.setMerchantAccountId(id);
        //没有选中默认商家
        lifeMerchantAccountAddressMapping.setAddressId(isNotEmpty(addressId) ? addressId : landId);
        lifeMerchantAccountAddressMappingMapper.insert(lifeMerchantAccountAddressMapping);

        operationRecordHelper.addBusinessLog(String.format("新增了商户 [%d] 的自提点信息", id));

        primaryCachePutter.deleteLifeById(id);
        return RestResult.success();
    }

    /**
     * 商家账号更改状态
     *
     * @param id
     * @param wrapper
     * @return
     */
    @Override
    public RestResult update(Long id, LifeMerchantAccountUpdateWrapper wrapper) {
        LifeMerchantAccount lifeMerchantAccount = lifeMerchantAccountMapper.selectById(id);
        if (isEmpty(lifeMerchantAccount)) {
            return RestResult.build(ResultEnum.NOT_FOUND);
        }

        new LambdaUpdateChainWrapper<>(lifeMerchantAccountMapper)
                .eq(LifeMerchantAccount::getId, id)
                .set(LifeMerchantAccount::getState, wrapper.getState())
                .set(LifeMerchantAccount::getUpdatedAt, new Date())
                .update();
        operationRecordHelper.addBusinessLog(String.format("更改了商户账号 [%d] 的状态", id));

        primaryCachePutter.deleteLifeById(id);
        return RestResult.success();
    }

}
